package com.ryzx.api.gateway.filter;

import com.ryzx.auth.vo.BapApiAuth;
import com.ryzx.common.util.RedisUtil;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Bean;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.HashMap;
import java.util.HashSet;
import java.util.List;

@Component
public class GlobalStartLoggerFilter implements GlobalFilter, Ordered {

//    @Resource
//    AntPathMatcher pathMatcher;

    @Bean
    public AntPathMatcher getMatcher(){
        return new AntPathMatcher();
    }

    @SuppressWarnings("unchecked")
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        String url = request.getURI().toString();
        boolean flag=false;
        if (!url.contains("/login"))  {
            List<String> tokenList = request.getHeaders().get("token");
            if (tokenList != null) {
                String token = tokenList.get(0);
                if (RedisUtil.hasKey(token)) {
                    HashMap<String, Object> hm = (HashMap<String, Object>) RedisUtil.get(token);
                    HashSet<BapApiAuth> hs = (HashSet<BapApiAuth>) hm.get("api");
                    flag= hs.stream().anyMatch(s -> getMatcher().match(s.getPath(), url));
                }
                if(flag){
                    if(RedisUtil.getExpire(token)<120)
                        RedisUtil.expire(token,1800);
                }
            }
        }else
            flag=true;
        if(flag){
            return chain.filter(exchange);
        }else{
            ServerHttpResponse response = exchange.getResponse();
            String redirectUrl = "/login";
            response.getHeaders().set(HttpHeaders.LOCATION, redirectUrl);
            //303状态码表示由于请求对应的资源存在着另一个URI，应使用GET方法定向获取请求的资源
            response.setStatusCode(HttpStatus.SEE_OTHER);
            response.getHeaders().add("Content-Type", "text/plain;charset=UTF-8");
            return response.setComplete();
        }

    }

    @Override
    public int getOrder() {
        return HIGHEST_PRECEDENCE;
    }
}